# coding=utf8


import ConfigParser

MODULE_NAME = 'client'

# GET CONFIG
config = ConfigParser.ConfigParser()
config.readfp(open(raw_input("config.ini"), "rb"))

db_host = config.get(MODULE_NAME, "DB_HOST")
db_port = config.get(MODULE_NAME, "DB_PORT")
db_name = config.get(MODULE_NAME, "DB_NAME")
db_user = config.get(MODULE_NAME, "DB_USER")
db_pass = config.get(MODULE_NAME, "DB_PASS")

# coding=utf8


import os
import ConfigParser
import MySQLdb
import xmltodict
import json


class Server(object):

    MODULE_NAME = 'server'

    def __init__(self, config_path):

        if os.path.exists(config_path) and os.path.isfile(config_path):
            config = ConfigParser.ConfigParser()
            config.read(config_path)
            self._db_host = config.get(self.MODULE_NAME, "DB_HOST")
            self._db_port = config.get(self.MODULE_NAME, "DB_PORT")
            self._db_name = config.get(self.MODULE_NAME, "DB_NAME")
            self._db_user = config.get(self.MODULE_NAME, "DB_USER")
            self._db_pass = config.get(self.MODULE_NAME, "DB_PASS")
        else:
            print "[%s]Config file parser error!" % self.MODULE_NAME

    @property
    def conn(self):
        try:
            conn = MySQLdb.connect(host=self._db_host,
                                   user=self._db_user,
                                   passwd=self._db_pass,
                                   db=self._db_name,
                                   port=int(self._db_port),
                                   charset="utf8")
            return conn
        except MySQLdb.Error,e:
             print "[%s]Mysql Error %d: %s" % (self.MODULE_NAME, e.args[0], e.args[1])

    def import_xml(self, xml_path):
        if os.path.exists(xml_path) and os.path.isfile(xml_path):
            converted_dict = xmltodict.parse(open(xml_path), encoding='utf-8');
            self._converted_dict = converted_dict
            print json.dumps(self._converted_dict)
        else:
            print "[%s]import xml error!" % self.MODULE_NAME

    def insert_db(self):
        if self._converted_dict != None:
            try:
                conn = self.conn
                cursor = conn.cursor()

                #insert event
                event_id = self._converted_dict["Event"]["@Event_id"]
                event_num = cursor.execute("select * from Event_info WHERE Event_id='%s'" % event_id)
                if event_num < 1:
                    cursor.execute("INSERT INTO Event_info(Event_id, Start_time, Start_time_frac, End_time, End_time_frac) "
                                   "VALUES ('%s', '%s', 0,'%s', 0)" %
                                   (event_id,
                                    self._converted_dict["Event"]["@StartTime"],
                                    self._converted_dict["Event"]["@EndTime"]))

                    conn.commit()

                #insert catalog
                catalogs = self._converted_dict["Event"]["catalog"]
                for catalog in catalogs:
                    cursor.execute(u"INSERT INTO Catalog"
                                   "(id, Event_id, Net_code, Save_time, Auto_flag, Operator, Loc_program, "
                                   "Eq_type, Sequen_name, O_time, O_time_frac, Epi_lat, Epi_lon, Epi_depth, Depfix_flag, M, "
                                   "M_source, SPmin, Dmin, Gap_azi, Rms, Erh, Erz, Qloc, Qnet, Qcom, Sum_stn, Loc_stn, Sum_pha, "
                                   "Loc_pha, Epic_id, Source_id, Location_cname, Location_sname, FE_num, FE_sname, FE_cname, "
                                   "Eq_name, Model_name, Lock_flag, Remark) "
                                   "VALUES "
                                   "('%s', '%s', '%s', '%s', '%s', '%s', '%s', "
                                   "'%s', '%s', '%s', %d, %g, %g, %g, %d, %g, "
                                   "'%s', %f, %g, %f, %f, %f, %f ,'%s','%s','%s', %d, %d, %d, "
                                   "%d, '%s', '%s', '%s', '%s', %d, '%s', '%s', "
                                   "'%s', '%s', '%s', '%s')" %
                                   (catalog["@id"],
                                    event_id,
                                    catalog["@Net_code"],
                                    catalog["@Save_time"],
                                    catalog["@Auto_flag"],
                                    catalog["@Operator"],
                                    catalog["@Loc_program"],
                                    catalog["@Eq_type"],
                                    catalog["@Sequen_name"],
                                    catalog["@O_time"],
                                    int(catalog["@O_time_frac"]),
                                    float(catalog["@Epi_lat"]),
                                    float(catalog["@Epi_lon"]),
                                    float(catalog["@Epi_depth"]),
                                    int(catalog["@Depfix_flag"]),
                                    float(catalog["@M"]),
                                    catalog["@M_source"],
                                    float(catalog["@SPmin"]),
                                    float(catalog["@Dmin"]),
                                    float(catalog["@Gap_azi"]),
                                    float(catalog["@Rms"]),
                                    float(catalog["@Erh"]),
                                    float(catalog["@Erz"]),
                                    catalog["@Qloc"],
                                    catalog["@Qnet"],
                                    catalog["@Qcom"],
                                    int(catalog["@Sum_stn"]),
                                    int(catalog["@Loc_stn"]),
                                    int(catalog["@Sum_pha"]),
                                    int(catalog["@Loc_pha"]),
                                    catalog["@Epic_id"],
                                    catalog["@Source_id"],
                                    catalog["@Location_cname"],
                                    catalog["@Location_sname"],
                                    int(catalog["@FE_num"]),
                                    catalog["@FE_sname"],
                                    catalog["@FE_cname"],
                                    catalog["@Eq_name"],
                                    catalog["@Model_name"],
                                    catalog["@Lock_flag"],
                                    catalog["@Remark"]))
                    conn.commit()
                cursor.close()
                conn.close()
            except MySQLdb.Error, e:
                print "[%s]insert_db Error %d: %s" % (self.MODULE_NAME, e.args[0], e.args[1])
            finally:
                self._converted_dict = None
                try:
                    cursor.close()
                    conn.close()
                except:
                    pass

    def push_to_server(self):
        if self._converted_dict != None:
            pass

    def exists(self, data):
        pass

    def confirm(self, confirm_data):
        pass


if __name__ == '__main__':
    server = Server("config.ini")
    server.import_xml("../data/ses.xml")
    server.insert_db()